package com.fsh.lingsp.common.common.intercepter;

import cn.hutool.core.collection.CollectionUtil;
import com.fsh.lingsp.common.common.domain.dto.RequestInfo;
import com.fsh.lingsp.common.common.exception.HttpErrorEnum;
import com.fsh.lingsp.common.common.utils.RequestHolder;
import com.fsh.lingsp.common.user.domain.enums.BlackTypeEnum;
import com.fsh.lingsp.common.user.service.cache.UserCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 作者：fsh
 * 日期：2024/03/06
 * <p>
 * 描述：拉黑拦截器。 用于用户登录后，判断该用户是否被拉黑。
 */
@Component
public class BlackIntercepter implements HandlerInterceptor {

    @Autowired
    private UserCache userCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取 黑名单列表
        Map<Integer, Set<String>> blackMap =userCache.getBlackMap();
        //获取登录用户
        RequestInfo requestInfo = RequestHolder.get();
        //判断是否在uid黑名单中
        if(inBlackList(requestInfo.getUid(),blackMap.get(BlackTypeEnum.UID.getType()))){
            HttpErrorEnum.IN_BLACKLIST.sendHttpError(response);
            return false;
        }
        return true;
    }

    /**
     * @param uid     UID
     * @param set uid黑名单集合
     *
     * 判断是否在uid黑名单中
     */
    private boolean inBlackList(Long uid, Set<String> set) {
        //不在
        if (Objects.isNull(uid) || CollectionUtil.isEmpty(set)){
            return false;
        }
        //在
        return set.contains(uid.toString());
    }

}
